package com.uminho.egendme;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;

import org.json.JSONException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.uminho.calendar.AppointmentDialog;
import com.uminho.exceptions.DestroyException;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.exceptions.NotAllowedError;
import com.uminho.exceptions.OAuthServiceFailureError;
import com.uminho.exceptions.SaveException;
import com.uminho.http.InternalStorage;
import com.uminho.http.Webservice;
import com.uminho.objects.Appointment;

/****c* egendme/Agenda
 * DESCRIPTION
 * Classe responsável por oferecer suporte à actividade Agenda
 *
 ****
 */


public class Agenda extends Activity {
	TextView agendaEmpty;
	Webservice w;
	ProgressDialog myProgressDialog = null; 
	Handler messages;
	ArrayList<ArrayList<Appointment>> listForAgenda;
	private ArrayList<Appointment> appointments;
	private LayoutInflater mInflater;


	/****f* Agenda/onCreate
	 * DESCRIPTION
	 * Método executado para criar a actividade
	 * INPUTS
	 * Estado da aplicação
	 * RESULT
	 * Actividade criada
	 ****
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.agenda);
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		agendaEmpty = (TextView) findViewById(R.id.agendaempty);
		actionBar.setHomeAction(new Action() {

			public void performAction(View view) {
				Intent i = new Intent(Agenda.this, Dashboard.class);
				startActivity(i);
			}

			public int getDrawable() {
				return R.drawable.icon1;
			}
		});
		actionBar.setTitle(R.string.agenda);

		appointments = new ArrayList();
		mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		myProgressDialog = ProgressDialog.show(this,getString(R.string.loading), getString(R.string.getagenda), true); 

		new Thread() {

			@Override
			public void run() {


				w = Webservice.getInstance();
				try {
					try {
						listForAgenda = w.getAgenda();
						saveAgenda();
						Log.d("Agenda",listForAgenda.toString());
						messages.sendEmptyMessage(1);
					} catch (SaveException e) {
						messages.sendEmptyMessage(-1);
						e.printStackTrace();
					} catch (DestroyException e) {
						messages.sendEmptyMessage(-1);
						e.printStackTrace();
					}
				} catch (NumberFormatException e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (MalformedURLException e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (IOException e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (InvalidOAuthParametersError e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (InvalidOAuthTokenError e) {
					messages.sendEmptyMessage(-2);
					e.printStackTrace();
				} catch (OAuthServiceFailureError e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (NotAllowedError e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (URISyntaxException e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				} catch (JSONException e) {
					messages.sendEmptyMessage(-1);
					e.printStackTrace();
				}


				// dismiss the progress dialog
				myProgressDialog.dismiss();


			}

		}.start();




		messages = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				if(msg.what==1){

					if(listForAgenda.size()==0){
						agendaEmpty.setText(R.string.agendaemptyappoint);
					}else{
						SimpleDateFormat format = new SimpleDateFormat("HH:mm");
						SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy");
						
						
						LinearLayout scrollable = (LinearLayout) findViewById(R.id.scrollable);
						
						for(ArrayList<Appointment> appoints: listForAgenda ){
							LinearLayout list = (LinearLayout) mInflater.inflate(R.layout.agendaday, null);
							list.removeAllViews();
							
							LinearLayout sepL = (LinearLayout) mInflater.inflate(R.layout.agendaseparator, null);
							GregorianCalendar d = appoints.get(0).getStartDate();
							TextView sep = (TextView) sepL.findViewById(R.id.textSeparator);
							sep.setText(dateFormat.format(d.getTime()));
							list.addView(sepL);
							for (Appointment a : appoints) {
								LinearLayout line = (LinearLayout) mInflater.inflate(R.layout.agendadescription, null);
				
								TextView textView1 = (TextView)line.findViewById(R.id.interval);
								TextView textView2 = (TextView)line.findViewById(R.id.text);
								
								GregorianCalendar g = a.getStartDate();
								String startHour = "", endHour="";
								
								startHour = format.format(g.getTime());
								g = a.getEndDate();
								endHour = format.format(g.getTime());
								
								textView1.setText(startHour+" - "+endHour+"  ");
								textView2.setText(a.getService().getTitle());
								
								line.setBackgroundResource(android.R.drawable.list_selector_background);
								line.setClickable(true);
								line.setFocusable(true);
								line.setTag(a);
								line.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										v.setBackgroundResource(android.R.drawable.list_selector_background);
										
										AppointmentDialog a = new AppointmentDialog(Agenda.this,(Appointment) v.getTag());
										a.show();
											//System.out.println("Clicked \""+a.getService().getTitle()+"\"");
									}
								});
								
								list.addView(line);
							}
							
							LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								     LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

							layoutParams.setMargins(0, 7, 0, 0);
							list.setLayoutParams(layoutParams);
							scrollable.addView(list);
						}
					}


				}else if(msg.what==-1){					
					loadAgenda();
					Toast.makeText(Agenda.this, R.string.connection_error, Toast.LENGTH_LONG);
					if(listForAgenda!=null)
						messages.sendEmptyMessage(1);
					else messages.sendEmptyMessage(-3);
				}
				else if(msg.what==-3){
					Toast.makeText(Agenda.this, R.string.connection_error, Toast.LENGTH_LONG).show();
					finish();
				}
				else{
					InternalStorage.deleteToken();
					Intent i = new Intent(Agenda.this,Login.class);
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			}};


	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//Log.d("Dashboard", "actvityRequest "+requestCode+" "+resultCode);
		if(resultCode==2){
			Log.d("Favorites", "finish");
			finish();
		}
		else if(resultCode==3){
			Log.d("Favorites", "refresh");
			Intent refresh = new Intent(this, Agenda.class);
			startActivity(refresh);
			this.finish();

		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	private void reload(){
		Intent refresh = new Intent(this, Agenda.class);
		startActivity(refresh);
		this.finish();
	}

	/****f* Agenda/saveAgenda
	 * DESCRIPTION
	 * Metodo executado para persistir o estado da Agenda
	 * RESULT
	 * Estado da agenda persistido
	 ****
	 */
	private void saveAgenda(){
		ObjectOutputStream outputStream = null;
		FileOutputStream fos=null;
		try {

			//Construct the LineNumberReader object
			fos = openFileOutput("agenda", Context.MODE_PRIVATE);
			outputStream = new ObjectOutputStream(fos);
			outputStream.writeObject(listForAgenda);
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			//Close the ObjectOutputStream
			try {
				if (outputStream != null) {
					outputStream.flush();
					outputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

	}

	/****f* Agenda/loadAgenda
	 * DESCRIPTION
	 * Método executado para carregar o estado da Agenda para memoria
	 * RESULT
	 * Estado da agenda em memoria
	 ****
	 */
	private void loadAgenda(){
		try {
			FileInputStream fis = openFileInput("agenda");
			if(fis!=null){
				ObjectInputStream ois = new ObjectInputStream(fis);
				this.listForAgenda = (ArrayList<ArrayList<Appointment>>) ois.readObject();
				ois.close();
				fis.close();}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}



}

